import functools

from flask import (
    Blueprint, flash, g, redirect, render_template, request, make_response, url_for,jsonify,session
)

from .db import get_db

bp = Blueprint('auth', __name__, url_prefix='/auth')

@bp.route('/login', methods=('POST',))
def login():
    if request.method == 'POST':
        username = request.json['username']
        password = request.json['password']

        db = get_db()
        cursor = db.cursor()
        # 查询用户
        cursor.execute(
            'SELECT * FROM users WHERE nickname = %s', (username,)
        )
        user = cursor.fetchone()

        print(user)

        if user is None or len(user) == 0:
            return jsonify({
                "msg": "登陆失败",
                "code": 403
            })

        elif  user[4] == password:
            print(user[3] + "登陆")
            # 创建响应对象
            response = make_response()
            # 设置 cookie
            response.set_cookie('user_id', value=str(user[0]), max_age=3600, samesite='None', secure=True)  # 一小时的秒数
            # 添加响应头
            session[user[0]] = user[0]  # 将用户 ID 存储在会话中
            print(session)
            return response

    return jsonify({
        "msg": "登陆失败",
        "code": 403
    })

@bp.route('/logout')
def logout():
    response = make_response(redirect(url_for('index')))
    response.delete_cookie('user_id')
    return response
